<?php 

session_start();

if (strtolower($_POST['authcode']) != $_SESSION['authcode']) {
    die(json_encode(array("code" => 0,"msg" => "验证码错误")));
} 

if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['authcode'])) {

    require("../../public/common.php");

    $username = trim($_POST['username']);

    $password = trim($_POST['password']);

    $query = mysqli_query($connect, "select count(id) as id from users where username='{$username}' and password='{$password}';");

    if (!$query) {
        die(json_encode(array("code" => 4,"msg" => "数据库查询失败")));
    }

    $result = mysqli_fetch_assoc($query);

    if ($result['id'] > 0 && strtolower($_POST['authcode']) == $_SESSION['authcode']) {

        $query_nick = mysqli_query($connect, "select nick from users where username='{$username}' and password='{$password}';");

        if (!$query_nick) {
            die(json_encode(array("code" => 4,"msg" => "数据库查询失败")));
        }

        $nick = mysqli_fetch_assoc($query_nick);

        $_SESSION['user'] = $nick["nick"];

        die(json_encode(array("code" => 2,"msg" => "登录成功")));

    } else {

        die(json_encode(array("code" => 1,"msg" => "用户名或密码错误")));

    }
} else {

    die(json_encode(array("code" => 5,"msg" => "服务器异常")));

}
